import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-16
 * Time: 14:35
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("启动服务器");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true){
            //对于tcp来说， 需要处理客户端发起的连接
            //通过读写clientSocket, 和客户端进行通信
            Socket clientSocket = serverSocket.accept(); //接通连接， 如果客户端没有发起连接, 这里会阻塞
            //如果是单线程， 阻塞等待在哪里等待客户端1输入， 这里就算客户端2发送请求连接， 也无法连接， 因为执行不到这里， 还在阻塞等待客户端1输入
            //线程池中取多个线程来执行多客户端连接请求
            Thread t = new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                ;
            });
            t.start();
        }
    }
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d]客户端上线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            Scanner scanner = new Scanner(inputStream); //inputstream套一层， 按照格式读入
            PrintWriter writer = new PrintWriter(outputStream); //outstream套一层， 按照格式写入
            while(true){ //一个连接可以发送多个请求
                //1.读取请求并解析
                if(!scanner.hasNext()){ //读取到空白字符之前都会阻塞默认没结束， 单线程执行到这里后客户端断开连接之前就阻塞到这里等待客户端1输入请求
                    System.out.printf("[%s:%d]客户端下线!\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                String request = scanner.next(); //读到\n结束
                //2.根据请求计算响应
                String response = process(request);
                //3.返回响应到客户端
                writer.println(response);
                writer.flush();
                // 打印日志
                System.out.printf("[%s:%d] req: %s, resp: %s\n", clientSocket.getInetAddress(), clientSocket.getPort(),
                        request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();   //没有请求后关闭客户端连接
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
